package com.code.lightning.commander;

import com.code.lightning.code.base.BasicDBConnect;
import com.code.lightning.sql.SqlHelper;
import com.github.freva.asciitable.AsciiTable;
import lombok.extern.slf4j.Slf4j;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 数据库操作
 * insert update delete select
 * @author LGX_TvT
 * @date 2021-02-10 21:20
 */
@Slf4j
public class SqlCommandFunction {
    // 退出
    private final static String EXIT_KEY = "EXIT";
    private final static String QUIT_KEY = "QUIT";

    /**
     * 执行SQL DDL DML
     * @throws IOException
     */
    public void run() throws IOException {
        Terminal terminal = TerminalBuilder.builder().dumb(true).build();
        LineReader lineReader = LineReaderBuilder.builder().terminal(terminal).build();
        String prompt = "SQL > ";
        // 字符串缓冲
        StringBuilder sb = new StringBuilder();
        while (true) {
            String line;
            try {
                line = lineReader.readLine(prompt);
                sb.append(line);
                String commandLine = sb.toString();
                // 退出
                if (SqlCommandFunction.EXIT_KEY.equalsIgnoreCase(commandLine) || SqlCommandFunction.QUIT_KEY.equalsIgnoreCase(commandLine)) {
                    System.out.println("Bye.");
                    break;
                }
                // 结束语句要以英文 ; 结尾
                if (!commandLine.endsWith(";")) {
                    continue;
                }
                sb.delete(0, sb.length());
                System.out.println("SQL => " + commandLine);
                log.info("SQL: {}", commandLine);
                // 执行SQL
                Map<String, Object> sqlResultMap = SqlHelper.executeSQL(BasicDBConnect.getConnect(), commandLine);
                log.info("SQL Result: {}",sqlResultMap);
                printResult(sqlResultMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 打印输出结果
     * @param map
     */
    public void printResult(Map map) {
        boolean success = (boolean) map.get("success");
        String message = (String) map.get("message");
        log.info(message);
        if (!success) {
            return;
        }
        List<Map<String,Object>> data = (List<Map<String, Object>>) map.get("data");
        if (data == null) {
            return;
        }
        // 获取所有列名
        List<String> columnNames = (List<String>) map.get(SqlHelper.COLUMN_KEY_CODE);

        // 获取所有列值
        List<List<String>> values = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            Map<String, Object> datum = data.get(i);
            List<String> lineValues = new ArrayList<>();
            for (int j = 0; j < columnNames.size(); j++) {
                lineValues.add(datum.get(columnNames.get(j)).toString());
            }
            values.add(lineValues);
        }

        String[] columnNamesArr = new String[columnNames.size()];
        String[][] valuesArr = new String[0][columnNames.size()];
        for (int i = 0; i < columnNames.size(); i++) {
            columnNamesArr[i] = columnNames.get(i);
        }

        if (values.size() != 0) {
            valuesArr = new String[values.size()][columnNames.size()];
            for (int i = 0; i < values.size(); i++) {
                for (int j = 0; j < values.get(i).size(); j++) {
                    valuesArr[i][j] = values.get(i).get(j);
                }
            }
        }

        String tableStr = AsciiTable.getTable(columnNamesArr, valuesArr);
        System.out.println(tableStr);
    }
}
